/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.helper;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Class for cryptographic functions.
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class Crypto 
{
  public static final String SALT = "&f2S2?d%sxaA...%%SY42Y!a";
  
  /**
   * Hashes a string using MD5. <br>
   * <b>MD5 is insecure. Use {@link #calculateSHAHash} instead.</b>
   */
  @Deprecated
  public static String calculateMD5Hash(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException
  {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(s.getBytes("UTF-8"));
    byte[] digest = md.digest();

    String hashVal = "";
    for(byte b : digest)
    {
      hashVal += String.format("%02x", b);
    }
    
    return hashVal;
  }
  
  /** Hashes a string using SHA. */
  public static String calculateSHAHash(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException
  {
    String withSalt = SALT + s;
    MessageDigest md = MessageDigest.getInstance("SHA");
    md.update(withSalt.getBytes("UTF-8"));
    byte[] digest = md.digest();

    String hashVal = "";
    for(byte b : digest)
    {
      hashVal += String.format("%02x", b);
    }
    
    return hashVal;
  }
}
